/*
 * Copyright (c) 2011 Nikolaus Moll (developer (at) miblounge (dot) net).
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * * Neither the name of the Jombi project nor the
 * names of its contributors may be used to endorse or promote products
 * derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL JOMBI BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
 * DAMAGE.
 */
package net.miblounge.jombi.impl.widgets;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

import org.jowidgets.common.types.DialogResult;
import org.jowidgets.common.types.FileChooserType;
import org.jowidgets.common.types.IFileChooserFilter;
import org.jowidgets.spi.widgets.IFileChooserSpi;
import org.jowidgets.spi.widgets.setup.IFileChooserSetupSpi;
import org.jowidgets.util.Assert;

import com.trolltech.qt.gui.QFileDialog;
import com.trolltech.qt.gui.QFileDialog.Filter;
import com.trolltech.qt.gui.QWidget;

public class FileChooserImpl implements IFileChooserSpi {

	private static final String WILD_CARD = "*.";

	private final FileChooserType type;
	private final QWidget parent;
	private final String title;
	private final QFileDialog.Filter filter;
	private String dir;
	private List<String> filenames;
	private QFileDialog.Option[] options;

	public FileChooserImpl(final Object parentUiReference, final IFileChooserSetupSpi setup) {
		parent = (QWidget) parentUiReference;
		type = setup.getType();
		if (setup.getTitle() != null) {
			title = setup.getTitle();
		} else {
			title = "";
		}

		filter = getFilter(setup.getFilterList());
	}

	private static Filter getFilter(final List<IFileChooserFilter> filterList) {
		if (filterList == null) {
			return new Filter("*.*");
		}

		// Scheme: "Images (*.png *.xpm *.jpg);;Text files (*.txt);;XML files (*.xml)";		

		final StringBuilder result = new StringBuilder();
		for (final IFileChooserFilter filter : filterList) {
			result.append(filter.getFilterName());
			result.append(" x(");

			for (final String extension : filter.getExtensions()) {
				result.append(WILD_CARD + extension + " ");
			}
			if (filter.getExtensions().size() > 0) {
				result.replace(result.length() - 1, result.length(), "");
			}

			result.append(");;");
		}

		if (result.length() > 2) {
			result.replace(result.length() - 2, result.length(), "");
		}

		return new Filter(result.toString());
	}

	@Override
	public Object getUiReference() {
		return null;
	}

	@Override
	public void setSelectedFile(final File file) {
		Assert.paramNotNull(file, "file");
		//fileDialog.setFilterPath(file.getAbsolutePath());
	}

	@Override
	public DialogResult open() {
		filenames = null;
		if (type == FileChooserType.OPEN_FILE) {
			final QFileDialog dlg = new QFileDialog(parent);
			dlg.setWindowTitle(title);
			//dlg.setFilter(filter);
			dlg.show();

			//			final String filename = QFileDialog.getOpenFileName(parent, title, dir, filter);
			//			if ((filename == null) || (filename.equals(""))) {
			//				filenames = new LinkedList<String>();
			//				filenames.add(filename);
			//			}
		} else if (type == FileChooserType.OPEN_FILE_LIST) {
			filenames = QFileDialog.getOpenFileNames(parent, title, dir, filter);
		} else if (type == FileChooserType.SAVE) {
			final String filename = QFileDialog.getSaveFileName(parent, title, dir, filter);
			if ((filename == null) || (filename.equals(""))) {
				filenames = new LinkedList<String>();
				filenames.add(filename);
			}
		}

		if ((filenames != null) && (filenames.size() > 0)) {
			return DialogResult.OK;
		} else {
			return DialogResult.CANCEL;
		}
	}

	@Override
	public List<File> getSelectedFiles() {
		final List<File> result = new LinkedList<File>();
		if (filenames != null) {
			for (final String fileName : filenames) {
				//				final String filterPath = fileDialog.getFilterPath();
				//				if (filterPath != null && !filterPath.trim().isEmpty()) {
				//					final File path = new File(filterPath);
				//					result.add(new File(path, fileName));
				//				} else {
				result.add(new File(fileName));
				//				}
			}
		}
		return result;
	}

	@Override
	public void setEnabled(final boolean enabled) {
		if (!enabled) {
			throw new IllegalArgumentException("Could not disable a file chooser");
		}
	}

	@Override
	public boolean isEnabled() {
		return true;
	}
}
